package com.service.imp;

import com.common.Base;
import com.common.Result;
import com.entity.Comment;
import com.entity.ArticleData;
import com.repository.CommentRepository;
import com.service.ArticleDataService;
import com.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @Author：Luohuiyong
 * @Description:
 * @Date: Created in 11:06 2019/1/9
 */
@Service
public class CommentServiceImp implements CommentService {

    @Autowired
    private CommentRepository commentRepository;

    @Autowired
    private ArticleDataService articleDataService;

    @Override
    public Comment findOne(int id){
        Optional<Comment> optionalUser = commentRepository.findById(id);
        return optionalUser.get();
    }

    /**
     * 根据文章id查找出所有的评论
     * @param articleId
     * @return
     */
    @Override
    public Result findAllByArticleId(int articleId){
        Sort sort = new Sort(Sort.Direction.DESC,"createdAt");
        List<Comment> list = commentRepository.findByArticleId(articleId,sort);

        return Base.success(list);
    }

    /**
     * 新增评论同时更新评论数
     * @param bean
     * @return
     */
    @Override
    @Transactional
    public Result create(Comment bean) {

        bean.setCreatedAt(new Date());
        commentRepository.save(bean);

        int commentNum = commentRepository.countByArticleId(bean.getArticleId());
        ArticleData articleData = new ArticleData();
        articleData.setCommentNum(commentNum);
        articleData.setArticleId(bean.getArticleId());
        articleDataService.updateCommentNum(articleData);

        return Base.success();
    }


}
